package cn.junior_programmer.springsecurityjdbc.filter;


import cn.junior_programmer.springsecurityjdbc.entity.LoginCondition;
import cn.junior_programmer.springsecurityjdbc.entity.LoginUser;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @author junior_programmer
 * <p>
 * <p>
 * 自定义身份校验过滤器
 */
public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    public CustomAuthenticationFilter(String loginDefaultUrl) {

        super(loginDefaultUrl);
    }

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {

        LoginCondition condition = JSON.parseObject(request.getInputStream(), LoginCondition.class);

        if (Objects.isNull(condition)) {
            throw new BadCredentialsException("未获取到登录Condition");
        }

        String username = validateUsername(condition.getUsername());
        String password = validatePassword(condition.getPassword());

        LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(username);

        if (!passwordEncoder.matches(password, loginUser.getPassword())) {

            throw new BadCredentialsException("账号密码不匹配");
        }

        return new UsernamePasswordAuthenticationToken(loginUser, password, loginUser.getAuthorities());
    }


    private String validateUsername(String username) {

        if (StringUtils.isNotBlank(username)) {

            return username.trim();
        }

        throw new BadCredentialsException("username不能为空");
    }

    private String validatePassword(String password) {

        if (StringUtils.isNotBlank(password)) {

            return password.trim();
        }

        throw new BadCredentialsException("password不能为空");
    }
}
